<template>
  <el-checkbox-group v-model="selectList">
    <div
      v-if="!loading"
      class="vc-image-list"
      :style="visual.parseStyle(compStyle)"
    >
      <div
        v-for="(data, index) in checkDataList"
        :key="index"
        class="vc-image-item"
        :style="itemStyle"
      >
        <el-image
          v-if="data['图片']"
          preview-teleported
          hide-on-click-modal
          :src="imageUrl + data['图片']"
          :preview-src-list="[imageUrl + data['图片']]"
          style="width:100%;height:100%"
          :fit="imageFit"
        />
        <div :style="checkboxStyle">
          <el-checkbox
            v-if="showCheckbox"
            :key="data.tempUuid"
            :value="data.tempUuid"
          ></el-checkbox>
        </div>
      </div>
    </div>
  </el-checkbox-group>
</template>

<script setup>
import {ref, watch, nextTick, computed, onMounted} from 'vue';
import visual from "@/visual/js/visual";
import tool from "@/utils/tool";

const props = defineProps({
  node: Object,
  compStyle: Object,
  compData: Object
});
const currNode = ref(props.node);
const dataList = ref([{}]);
const loading = ref(true);
const imageUrl = ref(import.meta.env.VITE_IMAGE_PATH);
const showCheckbox = ref(false);
const checkboxStyle = ref('');
const selectList = ref([]);
const itemStyle = ref('');
const imageFit = ref('cover');

const init = async() => {
  loading.value = true;
  if (currNode.value.compData.dataSourceType === '') {
    currNode.value.compData.dataSourceType = '静态数据';
  }
  const compStyle = props.compStyle || {};
  showCheckbox.value = compStyle['checkbox'] || false;
  checkboxStyle.value = 'position: absolute;' + (compStyle['checkbox.position'] || '');
  initItemStyle();
  await nextTick(() => loading.value = false);
};

const initItemStyle = () => {
  itemStyle.value = 'position: relative;';
  const compStyle = props.compStyle || {};
  imageFit.value = compStyle['image.fit'] || 'cover';
  itemStyle.value += 'width: ' + compStyle['image.width'] + ';';
  itemStyle.value += 'height: ' + compStyle['image.height'] + ';';
  return itemStyle.value;
};

const loadDataList = async() => {
  loading.value = true;
  dataList.value = (await visual.loadData(props.compData, {}, {}, currNode.value)).data || [];
  currNode.value.compData.dataList = JSON.stringify(dataList.value);
  await nextTick(() => loading.value = false);
};

const checkDataList = computed(() => {
  const resultList = tool.deepClone(dataList.value);
  resultList.forEach(data => {
    data.tempUuid = tool.uuids();
  })
  return resultList;
});

watch(() => props.compStyle, () => {
  init();
}, { deep: true });

watch(() => props.node.compData?.refresh, () => {
  loadDataList();
});

onMounted(async() => {
  await init();
  await loadDataList();
});
</script>

<style scoped>
.vc-image-item {
  :deep() {
    .el-checkbox {
      height: 14px!important;
    }
    .el-checkbox__label {
      padding-left: 0!important;
    }
  }
}
</style>